<template>
  <div>
    <div class="leftBox">
      <a-alert message="1. 拖动下面节点以排序" type="info" />
      <a-tree v-if="gData.length > 0" class="draggable-tree treeBox" draggable :tree-data="gData" @drop="onDrop" />
    </div>
    <div class="rightBox">
      <a-alert message="2. 配置节点校验信息" type="info" />
      <CheckNode ref="CheckNodeRef" class="treeBox" :f_nodeList="gData" />
    </div>
  </div>
</template>

<script>
export default {
  props: {
    treeList: {
      type: Array,
    },
  },
  data() {
    return {
      gData: this.generateData(this.treeList) || [],
      treeConfig: {
        sitetable: '',
        entsitetable: '',
        treeBuild: [],
      },
    }
  },
  created() {
    console.log('gData', this.gData)
  },
  methods: {
    // 父组件调用获取排序顺序
    f_getTreeList() {
      let g_check = { status: false, value: this.treeConfig }
      if (this.gData.length == 0) {
        this.$message.warning('请完成配置')
        return g_check
      }
      if (this.gData[0].key != 'SITE') {
        this.$message.warning('生产场地必须为顶级节点')
        return g_check
      }
      this.treeConfig.treeBuild = []
      console.log('this.gData', this.gData)
      this.recursionTree(this.gData, null)
      this.treeConfig.treeBuild = this.treeConfig.treeBuild.sort((a, b) => {
        if (a.sign < b.sign) {
          return -1
        } else {
          return 1
        }
      })
      console.log('构建完成', this.treeConfig.treeBuild)
      // 读取节点校验信息
      let node_check = this.$refs.CheckNodeRef.f_checkTreeNode()
      if (node_check?.status) {
        console.log('node_check', node_check)
      } else {
        return
      }

      // 存储到vuex里面去
      this.$store.commit('setAnalysisFacItemObj', ['treeConfig', this.treeConfig])
      this.$store.commit('setOriginalObj', ['TREELIST', this.gData])

      this.$store.commit('setAnalysisFacItemObj', ['check_node', node_check.value])
      this.$store.commit('setOriginalObj', ['TREECHECK', node_check.value])

      g_check.status = true
      return g_check
    },
    // 组装构建树配置
    recursionTree(treeData, f_node = null) {
      treeData.map((v) => {
        // 从表节点不处理
        if (v.subtable == false) {
          // 生产场地只取表名
          if (v.sign == 4) {
            this.treeConfig.sitetable = this.$store.state.com_config.analysisObj.factoryConfig.site_init.apltable
            this.treeConfig.entsitetable = this.$store.state.com_config.analysisObj.factoryConfig.site_init.enttable
          } else {
            const nodeKey = v.key.toLowerCase() + '_init'
            const fromresult = this.findSubtable(v.children)
            // console.log('从表', v.sign, fromresult, f_node,  this.$store.state.com_config.analysisObj.factoryConfig)
            let tempObj = {
              table: this.$store.state.com_config.analysisObj.factoryConfig[nodeKey].apltable,
              enttable: this.$store.state.com_config.analysisObj.factoryConfig[nodeKey].enttable,
              sign: v.sign,
              parentsign: f_node ? f_node.sign : null, // 取父级节点sign
              fromtable: fromresult != null ? fromresult.table : null,
              farelafield: this.$store.state.com_config.analysisObj.factoryConfig[nodeKey].sonrelafield,
              relafield: fromresult != null ? fromresult.field : null, // 与主表关联字段
              maprelation: this.$store.state.com_config.analysisObj.factoryConfig[nodeKey].maprelation,
            }
            this.treeConfig.treeBuild.push(tempObj)
          }
          // 递归
          if (v.children && v.children.length > 0) {
            this.recursionTree(v.children, v)
          }
        }
      })
    },
    // 查找从表
    findSubtable(children) {
      // console.log('children', children)
      if (children == null || children == undefined || children.length == 0) {
        return null
      } else {
        for (let v of children) {
          if (v.subtable) {
            const nodeKey = v.key.toLowerCase() + '_init'
            // console.log('找到了从表', v, this.$store.state.com_config.analysisObj.factoryConfig[nodeKey])
            return {
              table: this.$store.state.com_config.analysisObj.factoryConfig[nodeKey].apltable,
              field: this.$store.state.com_config.analysisObj.factoryConfig[nodeKey].farelafield,
            }
          }
        }
        return null
      }
    },
    // 格式化树数据
    generateData(treeList) {
      this.gData = []
      let vuexTreeList = this.$store.getters.getOriginalObj('TREELIST')
      if (vuexTreeList != null) {
        return vuexTreeList
      }
      for (let i = treeList.length - 1; i >= 0; i--) {
        if (treeList[i].isConfigurItem == false) {
          treeList.splice(i, 1)
          continue
        }
      }
      // console.log('treeList', treeList)
      return treeList
    },
    // 拖动事件
    onDrop(info) {
      console.log(info)
      const dropKey = info.node.eventKey
      const dragKey = info.dragNode.eventKey
      const dropPos = info.node.pos.split('-')
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
      const loop = (data, key, callback) => {
        data.forEach((item, index, arr) => {
          if (item.key === key) {
            return callback(item, index, arr)
          }
          if (item.children) {
            return loop(item.children, key, callback)
          }
        })
      }
      const data = [...this.gData]

      // Find dragObject
      let dragObj
      loop(data, dragKey, (item, index, arr) => {
        arr.splice(index, 1)
        dragObj = item
      })
      if (!info.dropToGap) {
        // Drop on the content
        loop(data, dropKey, (item) => {
          item.children = item.children || []
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.push(dragObj)
        })
      } else if (
        (info.node.children || []).length > 0 && // Has children
        info.node.expanded && // Is expanded
        dropPosition === 1 // On the bottom gap
      ) {
        loop(data, dropKey, (item) => {
          item.children = item.children || []
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.unshift(dragObj)
        })
      } else {
        let ar
        let i
        loop(data, dropKey, (item, index, arr) => {
          ar = arr
          i = index
        })
        if (dropPosition === -1) {
          ar.splice(i, 0, dragObj)
        } else {
          ar.splice(i + 1, 0, dragObj)
        }
      }
      console.log('拖拽后', data)
      this.gData = data
    },
  },
  components: {
    CheckNode: () => import('@/views/businessAssembly/public/spareparts/checkNode.vue'),
  },
}
</script>

<style scoped>
.treeBox {
  margin-top: 10px;
  border: 1px solid #eee;
  padding: 10px;
}
.leftBox {
  float: left;
  width: 49%;
}
.rightBox {
  float: right;
  width: 49%;
}
</style>
